package com.x.controller;

import cn.hutool.core.codec.Base64;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.x.model.FileInfo;
import com.x.model.UploadInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/upload")
public class UpLoadController {

    @Value("${upload.path}")
    private String uploadPath;
    @Value("${upload.domain}")
    private String domain;


    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo) {
        String name = uploadInfo.getName();
        name =  System.currentTimeMillis() + "_" + name;
        String base64 = uploadInfo.getBase64();//
        String[] strArray = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64.decode(strArray[1]);
        String path = uploadPath + name;
        FileUtil.writeBytes(bytes, path);
        return domain + "/images/" + name;
    }
       private static List<String> imgExts = CollUtil.newArrayList("jpg","png","gif","jpeg");
//    @GetMapping
//    public List<FileInfo> getFiles() {
//        List<String> names = FileUtil.listFileNames("D:/software/nginx-1.25.1/html/images/");
//        List<String> names2 = names.stream().filter(item -> {
//            String[] ext = StrUtil.splitToArray(item, '.');
//            return imgExts.contains(ext[ext.length - 1]);
//        }).collect(Collectors.toList());
//        List<FileInfo> fileInfos = names2.stream().map(name -> new FileInfo(name, domain + "/images/" + name)).collect(Collectors.toList());
//        return fileInfos;
//    }
//    @PostMapping
//    public String  upload(@RequestBody UploadInfo uploadInfo){
//         String   name = uploadInfo.getName();
//        name = IdUtil.fastSimpleUUID() + "_"+ name;
//         String  base64 = uploadInfo.getBase64();//
//         String[] strArray = StrUtil.splitToArray(base64, "base64,");
//         byte[] bytes = Base64.decode(strArray[1]);
//         String  path = uploadPath + name;
//         FileUtil.writeBytes(bytes,path);
//        return  domain + "/images/"+name;
//    }

    @GetMapping
    public  List<FileInfo>  getFiles(){
        List<String> names = FileUtil.listFileNames("D:/software/nginx-1.25.1/html/images/");

        List<FileInfo> fileInfos =
                names.stream()
                        .map(name -> new FileInfo(name, domain+"/images/" + name))
                        .collect(Collectors.toList());
        return  fileInfos;

    }
}
